<template>
  <el-dialog v-dialogDrag :visible.sync="dialogVisible" :title="title" width="750px" @close="resetForm('ruleForm')">
    <button-group ref="buttonGroup" @deleteCancel="deleteCancel" @submitForm="submitForm('ruleForm')" @cancel="dialogVisible = false" />
    <div class="formTopFont">采购发票清单</div>
    <el-row>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票编号" prop="invoiceNo">
              <el-input v-model="ruleForm.invoiceNo" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款信息" prop="paymentId">
              <el-select v-model="ruleForm.paymentId" style="width: 100%" @change="invoiceChange">
                <el-option v-for="item in invoiceList" :key="item.paymentId" :label="item.paymentNo" :value="item.paymentId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="type">
              <el-input v-model="ruleForm.type" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker v-model="ruleForm.invoiceDate" type="date" placeholder="选择日期" style="width: 100%" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票号码" prop="invoice">
              <el-input v-model="ruleForm.invoice" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供方名称" prop="supplierName">
              <el-input v-model="ruleForm.supplierName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-input v-model="ruleForm.currency" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票金额" prop="amount">
              <el-input-number v-model="ruleForm.amount" style="width: 100%" :max="9999999999" :precision="2" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="税率" prop="tax">
              <el-input-number v-model="ruleForm.tax" disabled style="width: 100%" :max="9999999999" :precision="2" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税金" prop="taxes">
              <el-input-number v-model="ruleForm.taxes" disabled style="width: 100%" :max="9999999999" :precision="2" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
  </el-dialog>
</template>
<script>
export default {
  props: {},
  data() {
    const checkInvoiceNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/purchase/invoice/verifyUnique?invoiceNo=${value}&id=${
          this.ruleForm.id || ''
        }`
      )
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback('发票编号重复！'))
      } else {
        return new Error(callback(res.data.msg))
      }
    }
    return {
      invoiceList: [],
      title: '',
      ruleForm: {
        paymentNo: '',
        paymentId: '',
        supplierId: '',
        supplierName: '', // 供方名称
        invoiceNo: '',
        type: '增值税发票',
        taxes: '',
        tax: '',
        amount: '',
        currency: '',
        invoice: '',
        invoiceDate: ''
      },
      rules: {
        paymentId: [
          { required: true, message: '付款信息不能为空！', trigger: 'change' }
        ],
        invoiceNo: [
          { required: true, message: '发票编号不能为空！', trigger: 'blur' },
          { validator: checkInvoiceNo, trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      obj: {}
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler(row) {
        row.taxes = +row.amount * +row.tax
      }
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      this.obj = row
      await this.getInvoiceList(row.id || '')
      if (row && row.hasOwnProperty('id')) {
        this.title = '编辑'
        this.ruleForm = Object.assign({}, row)
      } else {
        this.title = '新增'
      }
      this.dialogVisible = true
    },
    /* 获取所有付款单 */
    async getInvoiceList(id) {
      const res = await this.$axios.get(`/purchase/invoice/search?id=${id}`)
      if (res?.data.code === 200) {
        this.invoiceList = res.data.data
      }
    },
    invoiceChange($event) {
      const obj = this.invoiceList.find((el) => el.paymentId === $event)
      this.ruleForm = { ...this.ruleForm, ...obj }
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$axios.post(
            '/purchase/invoice/save',
            this.ruleForm
          )
          if (res?.data.code === 200) {
            this.$notify.success('提交成功！')
            this.dialogVisible = false
            this.$emit('getTableInfo')
          } else {
            this.$notify.error(res.data.msg)
          }
        }
      })
    },
    async deleteCancel() {
      this.$confirm(`确认删除数据？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios
            .delete(`/purchase/invoice/remove/${this.obj.id}`)
            .then((res) => {
              if (res.data.code === 200) {
                this.$notify.success('删除成功！')
                this.dialogVisible = false
                this.$emit('getTableInfo', 1)
              } else {
                this.$notify.error(res.data.msg)
              }
            })
        })
        .catch(() => {})
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.ruleForm = Object.assign({}, this.$options.data.call(this).ruleForm)
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
